package com.mycompany.project.client.chee;

import com.mycompany.project.client.*;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.ValueBoxBase.TextAlignment;
import com.google.gwt.user.client.ui.Widget;

/**
 * This class will provide the Logging Module tab GUI and functions
 * @author LeeNou
 *
 */
@SuppressWarnings("deprecation")
public class LoggingModuleGUI {
	
	//label on right
	private static HTML configurationLabel = new HTML("<center><font color =\"black\"> <marquee behavior=\"scroll\" direction=\"right\"><b>No possible configuration, yet</b></center></font></marquee>", true);
	private VerticalPanel loggingModuleMain = new VerticalPanel();
	private HorizontalPanel logHPanel = new HorizontalPanel();
	private VerticalPanel logVPanel = new VerticalPanel();
	private VerticalPanel btnVPanel = new VerticalPanel();//holds the module buttons
	private HorizontalPanel btnHPanel = new HorizontalPanel();//holds the module buttons
	private HorizontalPanel btnHPanel2 = new HorizontalPanel();//holds the module buttons
	//Module buttons
	static ToggleButton []m_button = new ToggleButton[Module.MAX_SIZE];
	//private ArrayList<ArrayList<Module>> mList;
	//labels
	private HTML buttonLabel = new HTML("<font size=\"-5\"><center>Please Select a Module</center></font>");
	//text box
	static TextBox codeNum = new TextBox();
	static TextBox posx = new TextBox();
	static TextBox posy = new TextBox();
	//listBox
	ListBox status = new ListBox();
	ListBox orientation = new ListBox();
	//add/update and clr btn
	ToggleButton addUpdateBtn = new ToggleButton("Add/Update");
	ToggleButton clrBtn = new ToggleButton("Clear");
	//horizontal panel to hold the orientation box and update/add and clr btn
	HorizontalPanel hPanelForThree = new HorizontalPanel();
	//Histogram
	private static Grid histogram = new Grid(10,2);
	private static HorizontalPanel moduleHisto[] = new HorizontalPanel[10];
	private ModuleType moduleType;
	private ScrollPanel mapScrollPanel = new ScrollPanel();
	//table
	public static FlexTable []modulesFlexTableAll = new FlexTable[11];
	private ScrollPanel sTablePanel = new ScrollPanel();
	
	public static HTML totalM = new HTML("");
	public static HTML currentM = new HTML();
	//GPS
	GPSData gpsData = new GPSData();
	private Button btnLoadGPS = new Button("Load GPS data");
	private static int countForPopUp = 0;
	private LoadSaveModuleDetailGUI lsMD;
	
	/**
	 * Constructor takes in the list of modules
	 * @param module_list
	 */
	public LoggingModuleGUI()
	{
		countForPopUp = 0;
		InitTable();
		//generate the modules for gps once.
		gpsData.generateModules();
		loggingModuleMain.setHorizontalAlign(HorizontalAlignment.CENTER);
		loggingModuleMain.add( btnVPanel);
		//loggingModuleMain.setStyleName("gbSilver");
		btnVPanel.add(buttonLabel);
		btnVPanel.add(btnHPanel);
		btnVPanel.add(btnHPanel2);
		//loggingModuleMain.setWidth("675px");
		loggingModuleMain.add(logHPanel);
		logHPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		logHPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_TOP);
		
		logHPanel.add(logVPanel);
		logHPanel.add(sTablePanel);
		loggingModuleMain.add(new HTML("<br></br>"));
		loggingModuleMain.add(totalM);
		loggingModuleMain.add(currentM);
		
		//load/ save module details panel
		lsMD = new LoadSaveModuleDetailGUI();
		loggingModuleMain.add(lsMD.getGUI());
		//add the load GPS data
		
		btnLoadGPS.setWidth("150px");
		loggingModuleMain.add(btnLoadGPS);
		initGPSBtn();
		
		//logHPanel.add(sLoadVPanel);
		totalM.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		totalM.setStyleName("fontSize10");
		currentM.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		currentM.setStyleName("fontSize10");
		
		totalM.setHTML("Total Module(s):"+(ModuleList.getTotalModules()) +
						"&nbsp&nbsp&nbsp&nbsp usable:"+ModuleList.getTotalUsableCount()+"&nbsp&nbsp&nbsp&nbsp usable After Repair:"+ModuleList.getTotalUsableAfterRepairCount()+
				"&nbsp&nbsp&nbsp&nbsp Beyond Repair:"+ModuleList.getTotalBeyondRepairCount());
		currentM.setHTML("Total XX Module(s):0"
				+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable:0"
				+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable After Repair:0"
				+"&nbsp&nbsp&nbsp&nbsp&nbsp  Beyond Repair:0");
		sTablePanel.add(modulesFlexTableAll[10]);
		
		initModuleButtons();
		init();
		initHistogram();
		turnOn(false);
		MapGUI.initMap();
		mapScrollPanel.setSize("780px", "300px");
		mapScrollPanel.add(MapGUI.getGrid());
		initBTN();
		initTextBox();
	}
	private void initGPSBtn()
	{
		btnLoadGPS.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				countForPopUp = 0;
				gpsData.loadGPSData();
				Window.alert("Load GPS data complete!");
			}
			
		});
	}
	public HTML getConfigLabel()
	{
		return configurationLabel;
	}
	private void InitTable()
	{
		for(int i=0;i<=ModuleList.getMlist().size();i++)
		{
			modulesFlexTableAll[i] = new FlexTable();
			modulesFlexTableAll[i].setWidth("330px");
			modulesFlexTableAll[i].setCellPadding(1);
			modulesFlexTableAll[i].setCellSpacing(3);
			modulesFlexTableAll[i].setHTML(0, 0, "<center><font size=\"1\">Code Number</font></center>");
			modulesFlexTableAll[i].setHTML(0, 1, "<center><font size=\"1\">Position</font></center>");
			modulesFlexTableAll[i].setHTML(0, 2, "<center><font size=\"1\">Status</font></center>");
		    modulesFlexTableAll[i].setHTML(0, 3, "<center><font size=\"1\">Orientation</font></center>");
		    modulesFlexTableAll[i].setHTML(0, 4, "<font size=\"1\">Delete</font>");
			
		}
	}
	
	public Widget getMapGUI()
	{
		return mapScrollPanel;
	}
	public static void TableInit(final Module m)
	{
		if(m_button[m.getModuleType().ordinal()].isDown())currentM.setHTML("Total "+m_button[m.getModuleType().ordinal()].getText()+" Module(s):"+ModuleList.getModuleTypeSize(m.getModuleType().ordinal())
				+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable:"+ModuleList.getModuleUsable(m.getModuleType().ordinal())
				+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable After Repair:"+ModuleList.getModuleUsableAfterRepair(m.getModuleType().ordinal())
				+"&nbsp&nbsp&nbsp&nbsp&nbsp  Beyond Repair:"+ModuleList.getModuleBeyondRepair(m.getModuleType().ordinal()));
		totalM.setHTML("Total Module(s):"+(ModuleList.getTotalModules()) +
				"&nbsp&nbsp&nbsp&nbsp usable:"+ModuleList.getTotalUsableCount()+"&nbsp&nbsp&nbsp&nbsp usable After Repair:"+ModuleList.getTotalUsableAfterRepairCount()+
		"&nbsp&nbsp&nbsp&nbsp Beyond Repair:"+ModuleList.getTotalBeyondRepairCount());
	//  totalModule.setHTML("<center>Total "+m_button[moduleType.ordinal()].getText()+" Module(s):"+mList.get(moduleType.ordinal()).size()+"</center>");
		if( ModuleList.getMlist().get(m.getModuleType().ordinal()).size() > 0) moduleHisto[m.getModuleType().ordinal()].remove(ModuleList.getMlist().get(m.getModuleType().ordinal()).size()-1);
		
		//adds in the amount to histogram
		moduleHisto[m.getModuleType().ordinal()].add(new Image(Module.getModuleFill(m.getModuleType().ordinal())));
		moduleHisto[m.getModuleType().ordinal()].add(new HTML(("<center>"+ModuleList.getMlist().get(m.getModuleType().ordinal()).size())+"</center>"));
		//add to map
		MapGUI.getGrid().setWidget(m.getPositionY(), m.getPositionX(),m);
		//display information about the module in that current location
		m.setTitle(m.getString());
		//clear the text area
		codeNum.setText("");
		posx.setText("");
		posy.setText("");
		
		// Add the module to the table.
	    int row = modulesFlexTableAll[m.getModuleType().ordinal()].getRowCount();
	    modulesFlexTableAll[m.getModuleType().ordinal()].setHTML(row, 0, "<center><font size=\"1\">"+m.getCodeNumber()+"</center></font>");
	    modulesFlexTableAll[m.getModuleType().ordinal()].setHTML(row, 1, "<center><font size=\"1\">("+m.getPositionX()+","+m.getPositionY()+")</center></font>");
	    modulesFlexTableAll[m.getModuleType().ordinal()].setHTML(row, 2, "<center><font size=\"1\">"+m.getStats()+"</center></font>");
	    modulesFlexTableAll[m.getModuleType().ordinal()].setHTML(row, 3, "<center><font size=\"1\">"+m.getOrientation()+"</center></font>");
	 // Add a button to remove this module from the table.
	    Button removeModBtn = new Button("x");
	    removeModBtn.addClickHandler(new ClickHandler() {
	      public void onClick(ClickEvent event) {
	    	  final int removedIndex = ModuleList.getMlist().get(m.getModuleType().ordinal()).indexOf(m);  
	    	  
	    	  //create pop up yes or no choice
	    	  
	    	    final DialogBox popUp = new DialogBox(false);
	      		final VerticalPanel popPanel = new VerticalPanel();
	      		final HorizontalPanel hPanel = new HorizontalPanel();
	      		final ToggleButton noBtn = new ToggleButton("no");
	      		noBtn.setWidth("50px");
	      		final ToggleButton yesBtn = new ToggleButton("yes");
	      		yesBtn.setWidth("50px");
	      		popPanel.add(new HTML("<center>Delete this module?</center>"));
	      		popPanel.add(hPanel);
	      		popUp.setWidget(popPanel);
	      		hPanel.add(yesBtn);
	      		hPanel.add(noBtn);
	      		popPanel.setHorizontalAlign(HorizontalAlignment.CENTER);
	      		hPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
	      		popUp.setPopupPosition(400, 100);
	      	    popUp.show();
	      	  yesBtn.addClickListener(new ClickListener(){

				@Override
				public void onClick(Widget sender) {
					// TODO Auto-generated method stub
					yesBtn.setDown(false);
        	    	  MapGUI.getGrid().clearCell(ModuleList.getMlist().get(m.getModuleType().ordinal()).get(removedIndex).getPositionY(), ModuleList.getMlist().get(m.getModuleType().ordinal()).get(removedIndex).getPositionX());
        	    	  ModuleList.getMlist().get(m.getModuleType().ordinal()).set(removedIndex, null);
        				ModuleList.getMlist().get(m.getModuleType().ordinal()).remove(removedIndex);
        				
        				moduleHisto[m.getModuleType().ordinal()].remove(ModuleList.getMlist().get(m.getModuleType().ordinal()).size()+1);
        				moduleHisto[m.getModuleType().ordinal()].add(new HTML("<center>"+ModuleList.getMlist().get(m.getModuleType().ordinal()).size()+"</center>"));
        				moduleHisto[m.getModuleType().ordinal()].remove(ModuleList.getMlist().get(m.getModuleType().ordinal()).size());
        				currentM.setHTML("Total "+m_button[m.getModuleType().ordinal()].getText()+" Module(s):"+ModuleList.getModuleTypeSize(m.getModuleType().ordinal())
								+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable:"+ModuleList.getModuleUsable(m.getModuleType().ordinal())
								+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable After Repair:"+ModuleList.getModuleUsableAfterRepair(m.getModuleType().ordinal())
								+"&nbsp&nbsp&nbsp&nbsp&nbsp  Beyond Repair:"+ModuleList.getModuleBeyondRepair(m.getModuleType().ordinal()));
        				totalM.setHTML("Total Module(s):"+(ModuleList.getTotalModules()) +
        						"&nbsp&nbsp&nbsp&nbsp usable:"+ModuleList.getTotalUsableCount()+"&nbsp&nbsp&nbsp&nbsp usable After Repair:"+ModuleList.getTotalUsableAfterRepairCount()+
        						"&nbsp&nbsp&nbsp&nbsp Beyond Repair:"+ModuleList.getTotalBeyondRepairCount());
        				modulesFlexTableAll[m.getModuleType().ordinal()].removeRow(removedIndex+1);
        				if(ModuleList.checkConfiguration() == 0) {
        					configurationLabel.setHTML("<center><font color =\"black\"><b> <marquee behavior=\"scroll\" direction=\"right\">No possible configuration, yet</b></center></font></marquee>");
        					ConfigurationGUI.setHabConfigBtn(false);
        					ConfigurationGUI.setHabConfigBtnMax(false);
        				}
        				else {
        					countForPopUp++;
        					ConfigurationGUI.setHabConfigBtn(true);
        					ConfigurationGUI.setHabConfigBtnMax(true);
        					if(countForPopUp == 1) {
        						//play min config possible sound
            					MHCSound.playMinConfig();
        						Window.alert("A minimum/maximum configuration is now possible!");
        					}
        					configurationLabel.setHTML("<center><font color =\"green\"> <marquee behavior=\"scroll\" direction=\"right\"><b>A minimum/maximum configuration is now possible!</b></center></font></marquee>");
        				}
        	    	  popUp.hide();
        	    	  //play module deleted sound
        	    	  MHCSound.playDeleteModule();
        	    	  ConfigurationGUI.clearConfigMapList();
        	  		  ConfigurationGUI.showAllChanges();
				}
	      	  });
	       		noBtn.addClickHandler(new ClickHandler() {
	       	        public void onClick(ClickEvent event) {
	       	        	if (noBtn.isDown()) {
	               			popUp.hide();
	               			noBtn.setDown(false);
	       	        	}
	       	        } });
				
	    	  //end of pop up
	      }
	    });
	    modulesFlexTableAll[m.getModuleType().ordinal()].setWidget(row, 4, removeModBtn);
	  //pop up
	  		if(ModuleList.checkConfiguration() == 0) {
	  			configurationLabel.setHTML("<center><font color =\"black\"><b> <marquee behavior=\"scroll\" direction=\"right\">No possible configuration, yet</b></center></font></marquee>");
	  			ConfigurationGUI.setHabConfigBtn(false);
	  			ConfigurationGUI.setHabConfigBtnMax(false);
	  		}
	  		else {
	  			countForPopUp++;
	  			ConfigurationGUI.setHabConfigBtn(true);
	  			ConfigurationGUI.setHabConfigBtnMax(true);
	  			if(countForPopUp == 1) {
	  				//play min config possible sound
	  				MHCSound.playMinConfig();
	  				Window.alert("A minimum/maximum configuration is now possible!");
	  			}
	  			configurationLabel.setHTML("<center><font color =\"green\"> <marquee behavior=\"scroll\" direction=\"right\"><b>A minimum/maximum configuration is now possible!</b></center></font></marquee>");
	  		}
	  		ConfigurationGUI.clearConfigMapList();
			ConfigurationGUI.showAllChanges();
	}
	public void initTextBox()
	{
		codeNum.addKeyboardListener(new KeyboardListener(){

			@Override
			public void onKeyDown(Widget sender, char keyCode, int modifiers) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onKeyPress(Widget sender, char keyCode, int modifiers) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onKeyUp(Widget sender, char keyCode, int modifiers) {
				// TODO Auto-generated method stub
				int count = 0;
				for(int h=0;h<codeNum.getText().length();h++){
					char temp = codeNum.getText().charAt(h);
					if(temp== '0' || temp == '1' || temp == '2' ||temp == '3' || temp == '4' || temp == '5' 
							|| temp== '6' || temp == '7' || temp == '8'||temp == '9' )
						count++;
				}
				if(count != codeNum.getText().length()) {
					Window.alert("Error: Code number needs to be an integer!");
					codeNum.setText("");
				}
				if(codeNum.getText().length() >5){
					Window.alert("Sorry! code number cannot exceed 5 digits!");
					codeNum.setText("");
				}
			}
			
		});
		
		posx.addKeyboardListener(new KeyboardListener(){

			@Override
			public void onKeyDown(Widget sender, char keyCode, int modifiers) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onKeyPress(Widget sender, char keyCode, int modifiers) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onKeyUp(Widget sender, char keyCode, int modifiers) {
				// TODO Auto-generated method stub
				int count = 0;
				for(int h=0;h<posx.getText().length();h++){
					char temp = posx.getText().charAt(h);
					if(temp== '0' || temp == '1' || temp == '2' ||temp == '3' || temp == '4' || temp == '5' 
							|| temp== '6' || temp == '7' || temp == '8'||temp == '9' )
						count++;
				}
				if(count != posx.getText().length()) {
					Window.alert("Error: x position needs to be an integer!");
					posx.setText("");
				}
				if(posx.getText().length()>0) 
				{
					if(Integer.parseInt(posx.getText()) >=MapGUI.COL){
						Window.alert("Sorry! x pos cannot exceed "+(MapGUI.COL-1)+"!");
						posx.setText("");
					}
				}
				if(posx.getText().equals("0") || (posx.getText().equals(""+Rover.getRoverCol()) && 
						posy.getText().equals(""+Rover.getRoverRow()))){
					Window.alert("Position x cannot be placed here!");
					posx.setText("");
				}
			}
			
		});
		
		posy.addKeyboardListener(new KeyboardListener(){

			@Override
			public void onKeyDown(Widget sender, char keyCode, int modifiers) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onKeyPress(Widget sender, char keyCode, int modifiers) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onKeyUp(Widget sender, char keyCode, int modifiers) {
				// TODO Auto-generated method stub
				int count = 0;
				for(int h=0;h<posy.getText().length();h++){
					char temp = posy.getText().charAt(h);
					if(temp== '0' || temp == '1' || temp == '2' ||temp == '3' || temp == '4' || temp == '5' 
							|| temp== '6' || temp == '7' || temp == '8'||temp == '9' )
						count++;
				}
				if(count != posy.getText().length()) {
					Window.alert("Error: y position needs to be an integer!");
					posy.setText("");
				}
				if(posy.getText().length()>0) 
				{
					if(Integer.parseInt(posy.getText()) >=MapGUI.ROW){
						Window.alert("Sorry! y pos cannot exceed "+(MapGUI.ROW-1)+"!");
						posy.setText("");
					}
				}
				if(posy.getText().equals("0") || (posx.getText().equals(""+Rover.getRoverCol()) && 
						posy.getText().equals(""+Rover.getRoverRow()))){
					Window.alert("Position y cannot be placed here!");
					posy.setText("");
				}
				
			}
			
		});
	}
	private boolean verify()
	{
		for(int i=0;i<ModuleList.getMlist().size();i++){
			for(int j=0; j < ModuleList.getMlist().get(i).size();j++){
				
				if(ModuleList.getMlist().get(i).get(j).getCodeNumber()== Integer.parseInt(codeNum.getText()) && i != moduleType.ordinal()){
					Window.alert("Error: A Different type of module already has this Code Number");
					codeNum.setText("");
					return false;
					}
				if(ModuleList.getMlist().get(i).get(j).getPositionX() == Integer.parseInt(posx.getText()) && ModuleList.getMlist().get(i).get(j).getPositionY() == Integer.parseInt(posy.getText()))
				{
					Window.alert("Error: Another Module is already at this x and y position");
					return false;
					}
				}
			}
		return true;
		}
	public void initBTN()
	{
		clrBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) 
			{
				if(clrBtn.isDown())
				{
					codeNum.setText("");
					posx.setText("");
					posy.setText("");
					clrBtn.setDown(false);
				}
			}
			
		});
		addUpdateBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) 
			{
				if(addUpdateBtn.isDown())
				{
					if(codeNum.getText().length() >0 && posx.getText().length() >0 && posy.getText().length() >0 )
					{
						final int code = Integer.parseInt(codeNum.getText());
						final int type = ModuleList.getModuleListType(code);
						final int index = ModuleList.getModule(code);
						if(type != -1 &&  index != -1 && type == moduleType.ordinal())//update same module
						{
							
							//ask user first before updating
							final DialogBox popUp = new DialogBox(false);
	        	      		 final VerticalPanel popPanel = new VerticalPanel();
	        	      		final HorizontalPanel hPanel = new HorizontalPanel();
	        	      		 final ToggleButton noBtn = new ToggleButton("no");
	        	      		noBtn.setWidth("50px");
	        	      		final ToggleButton yesBtn = new ToggleButton("yes");
	        	      		yesBtn.setWidth("50px");
	        	      		popPanel.add(new HTML("<center>Update this module?</center>"));
	        	      		popPanel.add(hPanel);
	        	      		popUp.setWidget(popPanel);
	        	      		hPanel.add(yesBtn);
	        	      		hPanel.add(noBtn);
	        	      		popUp.setPopupPosition(400, 100);
	        	      	    popUp.show();
	        	      	  yesBtn.addClickListener(new ClickListener(){

							@Override
							public void onClick(Widget sender) {
								yesBtn.setDown(false);
								//remove old module from map
								MapGUI.getGrid().clearCell(ModuleList.getMlist().get(moduleType.ordinal()).get(index).getPositionY(), ModuleList.getMlist().get(moduleType.ordinal()).get(index).getPositionX());
								//update module
								ModuleList.getMlist().get(type).get(index).setOrientation(orientation.getSelectedIndex());
								ModuleList.getMlist().get(type).get(index).setPositionX(Integer.parseInt(posx.getText()));
								ModuleList.getMlist().get(type).get(index).setPositionY(Integer.parseInt(posy.getText()));
								ModuleList.getMlist().get(type).get(index).setStats(status.getValue(status.getSelectedIndex()));
								currentM.setHTML("Total "+m_button[moduleType.ordinal()].getText()+" Module(s):"+ModuleList.getModuleTypeSize(moduleType.ordinal())
										+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable:"+ModuleList.getModuleUsable(moduleType.ordinal())
										+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable After Repair:"+ModuleList.getModuleUsableAfterRepair(moduleType.ordinal())
										+"&nbsp&nbsp&nbsp&nbsp&nbsp  Beyond Repair:"+ModuleList.getModuleBeyondRepair(moduleType.ordinal()));
								totalM.setHTML("Total Module(s):"+(ModuleList.getTotalModules()) +
										"&nbsp&nbsp&nbsp&nbsp usable:"+ModuleList.getTotalUsableCount()+"&nbsp&nbsp&nbsp&nbsp usable After Repair:"+ModuleList.getTotalUsableAfterRepairCount()+
										"&nbsp&nbsp&nbsp&nbsp Beyond Repair:"+ModuleList.getTotalBeyondRepairCount());
								//table update
								int row = ModuleList.getMlist().get(moduleType.ordinal()).indexOf(ModuleList.getMlist().get(moduleType.ordinal()).get(index))+1;
								modulesFlexTableAll[moduleType.ordinal()].setHTML(row, 0, "<center><font size=\"1\">"+codeNum.getText()+"</center></font>");
								modulesFlexTableAll[moduleType.ordinal()].setHTML(row, 1, "<center><font size=\"1\">("+posx.getText()+","+posy.getText()+")</center></font>");
								modulesFlexTableAll[moduleType.ordinal()].setHTML(row, 2, "<center><font size=\"1\">"+status.getItemText(status.getSelectedIndex())+"</center></font>");
								modulesFlexTableAll[moduleType.ordinal()].setHTML(row, 3, "<center><font size=\"1\">"+orientation.getItemText( orientation.getSelectedIndex())+"</center></font>");
								//re-add updated module to map
								MapGUI.getGrid().setWidget(Integer.parseInt(posy.getText()), Integer.parseInt(posx.getText()),ModuleList.getMlist().get(type).get(index));
								//display information about the module in that current location
								ModuleList.getMlist().get(type).get(index).setTitle(ModuleList.getMlist().get(type).get(index).getString()); 
								popUp.hide();
			        	    	//clear the text area
			  					codeNum.setText("");
			  					posx.setText("");
			  					posy.setText("");
			  					//play module updated sound
			  					MHCSound.playModuleUpdated();
			  					ConfigurationGUI.clearConfigMapList();
			  					ConfigurationGUI.showAllChanges();
			  					
							}
	        	      	  });
	        	       		noBtn.addClickHandler(new ClickHandler() {
	        	       	        public void onClick(ClickEvent event) {
	        	       	        	if (noBtn.isDown()) {
	        	               			popUp.hide();
	        	               			noBtn.setDown(false);
	        	               		//clear the text area
	        	    					codeNum.setText("");
	        	    					posx.setText("");
	        	    					posy.setText("");
	        	       	        	}
	        	       	        } });
							
						}
						else if (verify())//else add a new module
						{
							Module m = new Module();
							m.setModuleType(moduleType);
							//m.setUrl(Module.getModuleImage(moduleType.ordinal()));
							m.setCodeNumber(Integer.parseInt(codeNum.getText()));
							m.setOrientation(orientation.getSelectedIndex());
							m.setStats(status.getValue(status.getSelectedIndex()));
							m.setPositionX(Integer.parseInt(posx.getText()));
							m.setPositionY(Integer.parseInt(posy.getText()));
							ModuleList.addModule(m);
							m.setUrl(Module.getModuleImage(moduleType.ordinal()));
							//play module added sound
							MHCSound.playModuleAdded();
							TableInit(m);
							ConfigurationGUI.clearConfigMapList();
							ConfigurationGUI.showAllChanges();
						}
					}
					else
					{
						Window.alert("Please make sure all fields are filled!");
					}
					addUpdateBtn.setDown(false);
				}
			}
			
		});
	}
	public void turnOn(boolean enable)
	{
		codeNum.setEnabled(enable);
		codeNum.setText("");
		posx.setText("");
		posy.setText("");
		posx.setEnabled(enable);
		posy.setEnabled(enable);
		status.setEnabled(enable);
		orientation.setEnabled(enable);
		addUpdateBtn.setEnabled(enable);
		clrBtn.setEnabled(enable);
	}
	
	/**
	 * 
	 * @return this class's GUI
	 */
	public VerticalPanel getGUI()
	{
		return loggingModuleMain;
	}
	public static void initHistogram()
	{
		
		for(int i=0; i< 10; i++){
			if(moduleHisto[i] != null) moduleHisto[i].clear();//clear it if it's not null
			moduleHisto[i] = new HorizontalPanel();
		}
		
		histogram.clear();
		for (int row = 9; row >= 0; row--){
			moduleHisto[row].add(new HTML("<center>0</center>"));
			histogram.setWidget(row, 1, moduleHisto[row]);
			histogram.setWidget(row, 0, new Image(Module.getModuleImage(row)));
		}
	}
	/**
	 * 
	 * @return the panel which contains the histogram
	 */
	public Grid getHistogram()
	{
		return histogram;
	}
	/**
	 * 
	 */
	private void init()
	{
		//init table
		sTablePanel.setSize("350px","240px");
		
		//fix the width of all txt boxes
		codeNum.setWidth("123px");
		posx.setWidth("123px");
		posy.setWidth("123px");
		//logVPanel.add(totalModule);
		logVPanel.add(new HTML("<center><font size=\"1\">Code Number:</font></center>"));
		logVPanel.add(codeNum);
		codeNum.setAlignment(TextAlignment.CENTER);
		logVPanel.add(new HTML("<center><font size=\"1\">Position X:</font></center>"));
		logVPanel.add(posx);
		posx.setAlignment(TextAlignment.CENTER);
		logVPanel.add(new HTML("<center><font size=\"1\">Position Y:</font></center>"));
		logVPanel.add(posy);
		posy.setAlignment(TextAlignment.CENTER);
		logVPanel.add(new HTML("<center><font size=\"1\">Status:</font></center>"));
		logVPanel.add(status);
		logVPanel.add(new HTML("<font size=\"1\">Orientation:</font>"));
		logVPanel.add(orientation);
		hPanelForThree.add(addUpdateBtn);
		hPanelForThree.add(clrBtn);
		logVPanel.add(hPanelForThree);
		//initialize values for orientation and status listbox
		orientation.addItem("0");
	   	orientation.addItem("1");
	   	orientation.addItem("2");
	   	
	   	status.addItem("usable");
	   	status.addItem("usable after repair");
	   	status.addItem("beyond repair");
	}
	
	/**
	 * Creates all the module buttons and place them in the Gui
	 */
	private void initModuleButtons()
	{
		m_button[0] = new ToggleButton("Plain");
		m_button[1] = new ToggleButton("Control");
		m_button[2] = new ToggleButton("Power");
		m_button[3] = new ToggleButton("Food & Water");
		m_button[4] = new ToggleButton("Dormitory");
		m_button[5] = new ToggleButton("Canteen");
		m_button[6] = new ToggleButton("Sanitation");
		m_button[7] = new ToggleButton("Gym & Relaxation");
		m_button[8] = new ToggleButton("Airlock");
		m_button[9] = new ToggleButton("Medical");
		for( int i=0; i< Module.MAX_SIZE; i++)
		{
			m_button[i].setWidth("120px");
			//add each button to the vertical panel
			if(i < 5 )btnHPanel.add(m_button[i]);
			else btnHPanel2.add(m_button[i]);
			final int number = i;
			m_button[i].addClickHandler(new ClickHandler(){

				@Override
				public void onClick(ClickEvent event) {
					//When this button is press down,
					//all other buttons must be disable
					if (m_button[number].isDown()) {
						buttonLabel.setHTML("<font size=\"-5\"><center>"+m_button[number].getText()+" is locked</center></font>");
	   	        		for(int j=0; j< 10; j++){
	   	            		if( number != j) m_button[j].setEnabled(false);
	   	            	}
	   	        		//reset table
		   	            sTablePanel.remove(modulesFlexTableAll[10]);
		   	            sTablePanel.add(modulesFlexTableAll[number]);
		   	        	//end of table
	   	        		turnOn(true);
	   	        
	   	        		moduleType = Module.checkModuleType(number);
	   	        		currentM.setHTML("Total "+m_button[moduleType.ordinal()].getText()+" Module(s):"+ModuleList.getModuleTypeSize(moduleType.ordinal())
								+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable:"+ModuleList.getModuleUsable(moduleType.ordinal())
								+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable After Repair:"+ModuleList.getModuleUsableAfterRepair(moduleType.ordinal())
								+"&nbsp&nbsp&nbsp&nbsp&nbsp  Beyond Repair:"+ModuleList.getModuleBeyondRepair(moduleType.ordinal()));
					}
					else 
					{
						sTablePanel.remove(modulesFlexTableAll[number]);
						sTablePanel.add(modulesFlexTableAll[10]);
						buttonLabel.setHTML("<font size=\"-5\"><center>Please Select a Module</center></font>");
	   	        		for(int j=0; j< 10; j++){
	   	        			m_button[j].setEnabled(true);
	   	            	}
	   	        		turnOn(false);
	   	        		currentM.setHTML("Total XX Module(s):0"
								+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable:0"
								+"&nbsp&nbsp&nbsp&nbsp&nbsp  Usable After Repair:0"
								+"&nbsp&nbsp&nbsp&nbsp&nbsp  Beyond Repair:0");
					}
				}
				
			});
		}
	}
	
    public LoadSaveModuleDetailGUI getLsMD() {
        return lsMD;
    }
	
	

}
